<template>
  <div class="vue-echarts-wrapper">
    <div class="vue-chart-wrapper-canvas" ref="chartWrapper"></div>
  </div>
</template>

<script setup>
// import { defineProps, defineEmits } from "vue";
import {
  defineProps,
  defineEmits,
  ref,
  getCurrentInstance,
  onMounted,
  nextTick,
  watch,
  shallowRef,
  onUnmounted,
} from "vue";
import * as echarts from "echarts";
const emit = defineEmits(["click"]);
const instance = getCurrentInstance();
const chartWrapper = ref();
const chartInstance = shallowRef(null);
let resizeObserver = null;
const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

// 销毁图表实例
const disposeChart = () => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
};

// 创建图表
const createChart = () => {
  if (!chartWrapper.value) return;

  // 如果已存在实例，先销毁
  disposeChart();

  // 确保DOM已更新
  nextTick(() => {
    const wrapper = chartWrapper.value;
    // 强制设置容器样式
    wrapper.style.width = "100%";
    wrapper.style.height = "100%";

    chartInstance.value = echarts.init(wrapper);
    if (props.options) {
      chartInstance.value.setOption(props.options);
    }
    chartInstance.value.on("click", (e) => {
      emit("click", e);
    });
  });
};

// 更新图表
const updateChart = () => {
  if (!chartInstance.value || !props.options) return;

  nextTick(() => {
    try {
      chartInstance.value.setOption(props.options);
      chartInstance.value.resize();
    } catch (e) {
      console.error("更新图表失败:", e);
      // 如果更新失败，尝试重新创建图表
      createChart();
    }
  });
};

// 初始化ResizeObserver
const initResizeObserver = () => {
  if (!chartWrapper.value) return;

  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const { width, height } = entry.contentRect;
      if (width > 0 && height > 0 && chartInstance.value) {
        nextTick(() => {
          chartInstance.value?.resize();
        });
      }
    }
  });

  resizeObserver.observe(chartWrapper.value);
};

// 监听options变化
watch(
  () => props.options,
  () => {
    updateChart();
  },
  { deep: true }
);

onMounted(() => {
  createChart();
  initResizeObserver();
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
  disposeChart();
});
</script>

<style lang="scss" scoped>
.vue-echarts-wrapper {
  width: 100%;
  height: 100%;

  .vue-chart-wrapper-canvas {
    width: 100%;
    height: 100%;
  }
}
</style>
